<?php
namespace App\Controller;

use App\Logic\RelationLogic;

class RelationController extends ApiController
{
	private $relation = null;
	
	protected function _initialize()
	{
		parent::_initialize();
		
		$this->relation = new RelationLogic();
	}
	
	public function checkAction()
	{
		$query = array_merge(I('get.'),I('post.'));
		
		$raw = array();
		
		if( isset($query['neturl']) )
		{
			$query['neturl'] = str_replace('&amp;','&',$query['neturl']);
				
			$query['neturl'] = urldecode($query['neturl']);
		}
		
		// 验签
		if( $this->relation->checkSign($query) === false )
		{				
			$this->ajaxReturn(array('msg'=>'ERROR_SIGN','state'=>0));
		}
		
		// 检查必填参数
		$required = array('package','code','contract_id');
		
		if( $this->relation->checkRequire($required,$query) === false )
		{
			$this->ajaxReturn(array('msg'=>$this->relation->getError(),'state'=>0));
		}
		
		$data = $this->relation->getRelation($query);
		
		if( $data === false )
		{
			$raw = array('msg'=>$this->relation->getError(),'state'=>1,'data'=>NULL);
		}
		else
		{
			$raw = array('msg'=>'请求成功','state'=>1,'data'=>$data);
		}
		
		$this->ajaxReturn($raw);		
	}
	
	public function pushAction()
	{
		$query = I('post.');
		
		$raw = array();
		
		if( isset($query['neturl']) )
		{
			$query['neturl'] = str_replace('&amp;','&',$query['neturl']);
				
			$query['neturl'] = urldecode($query['neturl']);
		}
		
		// 检查必填参数
		$required = array('contract_id','neturl');
		
		if( $this->relation->checkRequire($required,$query) === false )
		{
			$this->ajaxReturn(array('msg'=>$this->relation->getError(),'state'=>0));
		}
		
		$data = $this->relation->pushRelation($query);
		
		if( $data === false )
		{
			$raw = array('msg'=>$this->relation->getError(),'state'=>1,'data'=>NULL);
		}
		else
		{
			$raw = array('msg'=>'请求成功','state'=>1,'data'=>$data);
		}
		
		$this->ajaxReturn($raw);
	}
	
	public function pullAction()
	{
		$query = array_merge(I('get.'),I('post.'));
		
		$raw = array();
		
		// 验签
		if( $this->relation->checkSign($query) === false )
		{
			$this->ajaxReturn(array('msg'=>'ERROR_SIGN','state'=>0));
		}
		
		// 检查必填参数
		$required = array('package','code','contract_id');
		
		if( $this->relation->checkRequire($required,$query) === false )
		{
			$this->ajaxReturn(array('msg'=>$this->relation->getError(),'state'=>0));
		}
		
		$data = $this->relation->pullRelation($query);
		
		if( $data === false )
		{
			$raw = array('msg'=>$this->relation->getError(),'state'=>1,'data'=>NULL);
		}
		else
		{
			$raw = array('msg'=>'请求成功','state'=>1,'data'=>$data);
		}
		
		$this->ajaxReturn($raw);
	}

}